<?php

class Ajax_UserProductsController extends Model3_Controller
{

    public function init()
    {
        $this->view->setUseTemplate(false);
    }

    public function saveAction()
    {
        $response = new stdClass();
        $response->res = false;
        $response->message = 'No se ha podido guardar el producto, intentelo nuevamente.';

        if ($this->getRequest()->isPost())
        {
            $post = $this->getRequest()->getPost();
            
            if (count($this->validProductDates($post))==0)
            {
                $userId = Model3_Auth::getCredentials('id');
                $em = $this->getEntityManager("DefaultDb");
                $productsAdapter = $em->getRepository('DefaultDb_Entities_Product');

                $catalogId = $this->getRequest()->getParam('id');

                $post['client'] = $em->find('DefaultDb_Entities_User', $userId);
                $post['catalog'] = $em->find('DefaultDb_Entities_Catalog', $catalogId);
                $post['newStartDate'] = new DateTime($post['newStartDate']);
                $post['newEndDate'] = new DateTime($post['newEndDate']);
                if(!isset($post['stock']))
                    $post['stock']=0;

                if(isset($post['ids']) && $post['variantsUse']==DefaultDb_Entities_Product::VARIANTS_USE)
                { //actualizamos las variantes
                    $productsVariantsAdapter = $em->getRepository('DefaultDb_Entities_ProductVariants');
                    $variants = $this->createArrayVariants($post['ids'],$post['descriptionVariant'],$post['stockVariant']);
                    unset($post['ids']);
                    unset($post['descriptionVariant']);
                    unset($post['stockVariant']);
                    $product=$productsAdapter->addProduct($post);
                    $result = $productsVariantsAdapter->updateVariantProduct($product, $variants);
                }
                else
                {  //actualizamos solamente el producto
                    $product = $productsAdapter->addProduct($post);
                }
                
                $idProduct = $product->getId();
                $response->idProduct = $idProduct;
                $response->res = true;
                $response->message = 'Producto Creado correctamente';
            }
        }

        $this->view->response = json_encode($response);
    }

    public function updateAction()
    {
        $response = new stdClass();
        $response->res = false;
        $response->message = 'No se ha podido guardar el producto, intentelo nuevamente.';

        if ($this->getRequest()->isPost())
        {
            $post = $this->getRequest()->getPost();
            if (count($this->validProductDates($post))==0)
            {               
                $userId = Model3_Auth::getCredentials('id');
                $em = $this->getEntityManager("DefaultDb");
                $productsAdapter = $em->getRepository('DefaultDb_Entities_Product');

                $catalogId = $this->getRequest()->getParam('id');
                $productId = $this->getRequest()->getParam('idProduct');

                $post['client'] = $em->find('DefaultDb_Entities_User', $userId);
                $post['catalog'] = $em->find('DefaultDb_Entities_Catalog', $catalogId);
                $post['newStartDate'] = new DateTime($post['newStartDate']);
                $post['newEndDate'] = new DateTime($post['newEndDate']);

                if(isset($post['ids'])&& $post['variantsUse']==DefaultDb_Entities_Product::VARIANTS_USE)
                { //actualizamos las variantes
                    $productsVariantsAdapter = $em->getRepository('DefaultDb_Entities_ProductVariants');
                    $variants = $this->createArrayVariants($post['ids'],$post['descriptionVariant'],$post['stockVariant']);
                    unset($post['ids']);
                    unset($post['descriptionVariant']);
                    unset($post['stockVariant']);
                    $productsAdapter->updateProduct($productId, $post);
                    $product = $productsAdapter->find($productId);
                    $result = $productsVariantsAdapter->updateVariantProduct($product, $variants);
                }
                else
                {  //actualizamos solamente el producto
                    $productsAdapter->updateProduct($productId, $post);
                }
                $response->res = true;
                $response->message = 'Producto actualizado correctamente';
            }
        }

        $this->view->response = json_encode($response);
    }

    private function validProductDates($dates)
    {
        $errors = array();

        if (!isset($dates['name']))
        {
            $errors[] = 'El campo nombre es obligatorio';
        }
        elseif (trim($dates['name']) == '')
        {
            $errors[] = 'El campo nombre no debe estar vacio';
        }

        if (!isset($dates['price']))
        {
            $errors[] = 'El campo precio es obligatorio';
        }
        elseif (trim($dates['price']) == '')
        {
            $errors[] = 'El campo precio no debe estar vacio';
        }

        if (!isset($dates['stock']) && $dates['variantsUse']==DefaultDb_Entities_Product::VARIANTS_NOT_USE)
        {
            $errors[] = 'El campo existencia es obligatorio';
        }
        elseif (isset($dates['stock']) && trim($dates['stock']) == '')
        {
            $errors[] = 'El campo existencia no debe estar vacio';
        }

        return $errors;
    }

    public function uploadImageAction()
    {
        $info = array();
        $this->view->setUseTemplate(false);
        $em = $this->getEntityManager("DefaultDb");
        $productsAdapter = $em->getRepository('DefaultDb_Entities_Product');
        $userId = Model3_Auth::getCredentials('id');

        if ($this->getRequest()->isPost())
        {

            $post = $this->getRequest()->getPost();
            $idProducto = $post['idProducto'];
            $numImgByProd = $post['numImgByProd'];

            $idUsuario = Model3_Auth::getCredentials('id');

            if (!empty($_FILES))
            {
                $product = $productsAdapter->find($idProducto);
                if ($product instanceof DefaultDb_Entities_Product)
                {

                    $upload = $_FILES['archivos'];
                    foreach ($upload['tmp_name'] as $index => $value)
                    {
                        //                    if (count($imagenes) < $numImgByProd)
                        //                    {
                        $info = $this->handle_file_upload(
                                $upload['tmp_name'][$index], $upload['name'][$index], $upload['size'][$index], $upload['type'][$index], $upload['error'][$index], $userId, $idProducto, 0, // index
                                $product
                        );
                        //                    }
                        //                    else
                        //                    {
                        //                        $info['errorImg'] = 'La imagen ' . $upload['name'][$index] . ' no ha sido cargada. Fuera del limite de imagenes permitidas';
                        //                    }
                    }
                }
                else
                {
                    $info['errorImg'] = 'El producto no existe';
                }
            }
        }

        $this->view->info = json_encode($info);
    }

    private function handle_file_upload($uploaded_file, $name, $size, $type, $error, $idUsuario, $idProducto, $indexImagenes, $product)
    {
        $em = $this->getEntityManager("DefaultDb");
        $imagesAdapter = $em->getRepository('DefaultDb_Entities_ProductImages');
        $info = array();

        $dirUpload = 'data/images/usr' . $idUsuario . '/';
        $subTipo = explode('/', $type);
        $ext = explode('.', $name);

        $pathImage = $dirUpload . 'img' . '_' . $idProducto . '_' . date('YmdHis') . '_' . $indexImagenes . '.' . $ext[count($ext) - 1];

        if ($size > DefaultDb_Entities_ProductImages::IMG_MAX)
        {
            $info['errorImg'] = 'Ocurrio un error al procesar la imagen...';
        }
        else
        {
            if ($subTipo[0] == 'image')
            {
                $fs = new Model3_FileSystem();
                if (!$fs->existeDir($dirUpload))
                {
                    $fs->creaDir($dirUpload);
                }

                $res = move_uploaded_file($uploaded_file, $pathImage);
                if ($res)
                {

                    $data = array(
                        'path' => $pathImage,
                        'indexOrder' => $indexImagenes,
                        'product' => $product
                    );

                    $res = $imagesAdapter->addImage($data);
                    $info = array('name' => $name, 'type' => $type, 'size' => $size, 'successImg' => 'La imagen ' . $name . ' ha sido cargada correctamente');

                    $imagenes = $product->getImages();
                    $this->view->imagenes = $imagenes;
                }
                else
                {
                    $info['errorImg'] = 'Ocurrio un error al procesar la imagen...';
                }
            }
            else
            {
                $info['errorImg'] = 'Solo se pueden subir imagenes. El archivo ' . $name . ' no se cargo';
            }
        }

        return $info;
    }
    public function createArrayVariants($ids,$variants,$stocks)
    {
        $array = array();
        foreach($ids as $key => $id)
            $array[$id]=array('description'=>$variants[$key],'stock'=>$stocks[$key]);
        return $array;
    }

}

?>
